import { EventName } from "./EventName";

//------------------------------------------------------------
// * Author         : Ekko
// * Description    : 全局事件
//------------------------------------------------------------

export class GlobalEvent {
    private static inst: GlobalEvent;
    private listeners: any;

    private constructor(){
        this.listeners = {};
    }

    static getInst(): GlobalEvent{
        if(!this.inst){
            this.inst = new GlobalEvent();
        }
        return this.inst;
    }

    fire(event:EventName, ...params: any[]): void{
        let cbs: any[] = this.listeners[event];
        if(!cbs){
            return;
        }

        for(let i: number = 0, len: number = cbs.length; i < len; i += 2){
            let cb: any = cbs[i];
            let host: any = cbs[i + 1];
            cb.call(host, ...params);
        }
    }

    add(event: EventName, cb: Function, host: any = null): void{
        let cbs: any[] = this.listeners[event];
        if(!cbs){
            this.listeners[event] = cbs = [];
        }
        cbs.push(cb, host);
    }

    remove(event: EventName, cb: Function){
        let cbs: any[] = this.listeners[event];
        if(!cbs){
            return;
        }
        let index: number = cbs.indexOf(cb);
        if(index < 0){
            cc.warn("GlobalEvent remove ", event, ", but cb not exists!");
            return;
        }
        cbs.splice(index, 2);
    }

    clear(){
        for(let key in this.listeners){
            this.listeners[key].length = 0;
        }
        this.listeners = {};
    }
}